<template>
	<view class="post" :class="[isDark?'dark':'', $store.state.AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','max-height':isDark?'120vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'},{top:jpHeight + 'px'}]" v-if="showContent">
			<view class="cu-bar" :class="isDark?'dark':'bg-white'" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px','background-color':isDark?'#1c1c1c':'#ffffff'}">
				<view class="action" @tap="isback">
					<text class="cuIcon-back"></text> 
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					<block v-if="type=='edit'">
						{{$t('edit.addshop.editproduct')}}
					</block>
					<block v-else>
						{{$t('global.publishproduct')}}
					</block>
				</view>

			</view>
		</view>
		<view :style="[{padding:(NavBar+10) + 'px 10px 0px 10px'}]"></view>
		<form>
			<view class="cu-form-group margin-sm" :class="isDark?'dark':'bg-white'" :style="'border-radius: 20upx;background-color:'+(isDark?'#1c1c1c':'#ffffff')">
				<input placeholder="$t('edit.addshop.plsproducttitle')" name="input" v-model="title" :adjust-position="false" :focus="false"/>
				<!-- <block v-if="type=='add'">
					<view class="picker" @tap="toCategory">
						<block v-if="sectionName=='$t('global.unknowncircle')'">
							{{$t('global.selectcircle')}}
						</block>
						<block v-else>
							<text class="text-shojo">{{sectionName}}</text>
						</block>
					</view>
				</block> -->
			</view>
			<view class="margin-sm" :class="isDark?'dark':'bg-white'" :style="'border-radius: 20upx;background-color:'+(isDark?'#1c1c1c':'#ffffff')">
				<view class="margin-sm">
					<cu-editor ref="editor" :mrPoster="videoPoster" :SPimg="SPimg" :musicpic='musicpic'
						editorId='editor' :NavBar="NavBar" @editorFocus="handleEditorFocus" :uploadTime="uploadTime"
						@editorBlur="handleEditorBlur" :url="this.$API.upload()" :formData="formData" :content="text"
						:MusicUpload='MusicUpload' :isPay="true" placeholder="$t('edit.addshop.plsproductintro')" :isWz="false"
						@save="onSave"></cu-editor>
				</view>

			</view>
			<view class="margin-sm" :class="isDark?'dark':'bg-white'" :style="'border-radius: 20upx; padding: 14px;background-color:'+(isDark?'#1c1c1c':'#ffffff')+';'+(showContent?'':'display:none')">
				<view class="margin-top-sm">
					<tn-button :backgroundColor="isDark?'#2c2c2c':'#f6f6f6'" fontColor='#444' width='100%'
						@click="editPaidContent">{{$t('edit.addshop.editpaytxt')}}</tn-button>
				</view>
			</view>
			<view :style="showContent?'':'display:none'">
				<view class="margin-sm" :class="isDark?'dark':'bg-white'" :style="'font-size: 30upx;padding: 20upx;border-radius: 20upx;background-color:'+(isDark?'#1c1c1c':'#ffffff')">

					<view class="margin-sm">
						<view style="display: flex; justify-content: space-between; align-items: center;">
							<text>{{$t('edit.addshop.stocknum')}}</text>
							<view style="flex: 1; display: flex; justify-content: flex-end;">
								<input v-model="num" type="number" placeholder="$t('edit.addshop.plsstocknum')"
									style="width: 130px; text-align: right;margin-right: 5px;" /><span>{{$t('edit.addshop.piece')}}</span>
							</view>
						</view>
					</view>
					<hr style="width: 100%;margin: auto;height: 1px;background: #e5e5e5d9;border: none;" />
					<view class="margin-sm" @click="sortShow=true">
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view>{{$t('edit.addshop.goodcategory')}}</view>
							<view>
								<blcok v-if="sortText==''">
									{{$t('edit.addshop.unselect')}}
								</blcok>
								<blcok v-else>
									{{sortText}}
								</blcok>
							</view>
						</view>
					</view>
					<hr style="width: 100%;margin: auto;height: 1px;background: #e5e5e5d9;border: none;" />
					<view class="margin-sm" @click="setSubtypeShow()">
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view>{{$t('edit.addshop.subcategory')}}</view>
							<view>
								<blcok v-if="subtypeText==''">
									{{$t('edit.addshop.unselect')}}
								</blcok>
								<blcok v-else>
									{{subtypeText}}
								</blcok>
							</view>
						</view>
					</view>
					<hr style="width: 100%;margin: auto;height: 1px;background: #e5e5e5d9;border: none;" />
					<view class="margin-sm">
						<view style="display: flex; justify-content: space-between; align-items: center;">
							<view>{{$t('edit.addshop.productcover')}}</view>
							<tn-button :backgroundColor="isDark?'#2c2c2c':'#f6f6f6'" @click="imgUpload()" fontColor='#444'>{{$t('edit.addshop.upload')}}</tn-button>
						</view>
						<view v-if="imgurl" class="margin-top-sm">
							<tn-lazy-load borderRadius="20upx" :image="imgurl" mode="widthFix" width="100%"
								height="348px" @tap="previewImage(imgurl,imgurl)"></tn-lazy-load>
						</view>
					</view>

				</view>
				<view v-if="type=='add'" class="margin-sm">
					<tn-button type="button" :backgroundColor="isDark?'#2c2c2c':'#01BEFF'" fontColor="#fff" width="100%"
						class="form-btn" @click="submit()">
						{{$t('global.publishproduct')}}
					</tn-button>
				</view>
				<view v-else class="margin-sm">
					<tn-button type="button" :backgroundColor="isDark?'#2c2c2c':'#01BEFF'" fontColor="#fff" width="100%"
						class="form-btn" @click="submit()">
						<block v-if="draft==0">
							{{$t('edit.addshop.editproduct')}}
						</block>
						<block v-if="draft==1">
							{{$t('global.publishproduct')}}
						</block>
					</tn-button>
				</view>
			</view>
		</form>
		<tn-select v-model="sortShow" title="$t('edit.addshop.plsbigcategory')" :list="sortSelect" @confirm="sortConfirm"></tn-select>
		<tn-select v-model="subtypeShow" title="$t('edit.addshop.plssubcategory')" :list="subtypeSelect" @confirm="subtypeConfirm"></tn-select>

	</view>
</template>

<script>
	import mpHtml from '@/components/mp-html/mp-html'
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	var wv;
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,
				isPaid: false,
				modalName: "",
				sortShow: false,
				subtypeShow: false,
				showContent: true,
				havePay: false,
				uid: 0,
				token: "",
				poster: this.$API.SPmusicpic(),
				isShow: false,
				show: false,
				isPayShop: false,
				name: "",
				sortSelect: [],
				subtypeSelect: [],
				sortList: [],
				sortText: "",
				subtypeText: "",
				subtypeList: [],
				title: "",
				category: "",
				metaList: "",
				imgurl: "",
				num: "",
				sort: 0,
				subtype: 0,
				curHeight: 0,
				shopPrice: "",
				subtypeText: "",
				jpHeight: 0,
				screenHeight: 0,
				postheight: 0,
				poststyle: "",
				readstyle: "",
				isText: 0,
				shopCategoryList: [],

				uploadTime: this.$API.getuploadTime(),
				draft: 0,
				MusicUpload: this.$API.SPstarMusicUpload(),
				musicpic: this.$API.SPmusicpic(),
				videoPoster: this.$API.getVideoPoster(),
				SPimg: this.$API.SPimgs(),
				formData: {},
				//文章表单部分
				title: "",
				category: 1,
				tag: "",
				categoryText: "",
				text: '',
				textRead: "",
				isLoading: false,
				isSpace: false,
				//页面状态
				type: "add",
				id: 0,
				lenght: 0,
				payId: 0,
				shopList: [],
				editInterval: null,
				shopID: -1,
				sectionName: $t('global.unknowncircle'),
				sectionid: 0,
				content: "",
			}
		},
		onPullDownRefresh() {

		},
		onShow() {

		},
		onHide() {
			var that = this;
			clearInterval(that.editInterval);
			that.editInterval = null;
		},
		onShow() {
			var that = this;
			if (localStorage.getItem('userinfo')) {
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.token = userInfo.token;
				if (userInfo.screenName) {
					that.name = userInfo.screenName;
				} else {
					that.name = userInfo.name;
				}
				that.formData = {
					'token': userInfo.token,
					'username': that.name
				}
			}
			if (localStorage.getItem('curSection')) {
				var curSection = JSON.parse(localStorage.getItem('curSection'));
				that.sectionid = curSection.id;
				that.sectionName = curSection.name;
				localStorage.removeItem('curSection');
			}
			uni.$emit('tOnLazyLoadReachBottom');

		},
		onLoad(res) {
			var that = this;
			localStorage.setItem('isSaveSp', "false");
			that.editInterval = setInterval(function() {
				if (localStorage.getItem('goBack')) {
					localStorage.removeItem('goBack');
					that.back();
				}
			}, 500);
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			if (res.draft) {
				that.draft = res.draft;
			}
			if (res.type=='edit') {
				that.type = 'edit';
			}else{
				that.type = 'add';
			}
			
			that.setloading();
			var timer = setTimeout(function() {
				that.getShopTypelist();
			}, 500)
		
			if (that.type == 'edit') {
				if (!res.id) {
					uni.showToast({
						title: that.$t('edit.addshop.paranoempty'),
						icon: 'none'
					});
					that.back();
					return false;
				} else {
					that.id = res.id;
					that.setloading();
					var timer = setTimeout(function() {
						that.getInfo(that.id);
					}, 500)
				}
			}
			if (res.section) {
				that.sectionName = res.section;
			}
			if (res.sectionid) {
				that.sectionid = res.sectionid;
			}
			var verifyLevel = 0;
			if (localStorage.getItem('AppInfo')) {
				try {
					var AppInfo = JSON.parse(localStorage.getItem('AppInfo'));
					verifyLevel = AppInfo.verifyLevel;
				} catch (e) {
					console.log(e);
				}
			}
			if (localStorage.getItem('userinfo')) {
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.token = userInfo.token;
				that.uid = userInfo.uid;
				that.uid = userInfo.uid;
				if (userInfo.screenName) {
					that.name = userInfo.screenName;
				} else {
					that.name = userInfo.name;
				}
			}
		},
		methods: {
			subtypeConfirm(e) {
				var that = this;
				that.subtype = e[0].value;
				that.subtypeText = e[0].label;
			},
			sortConfirm(e) {
				var that = this;
				that.sort = e[0].value;
				that.sortText = e[0].label;
				for (var s in that.sortList) {
					if (that.sortList[s].id == that.sort) {
						that.setSort(that.sortList[s], true);
					}
				}
			},
			imgUpload() {
				let that = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					success: function(res) {
						uni.showLoading({
							title: that.$t('common.loadmore')
						});
						const tempFilePaths = res.tempFilePaths;
						const uploadTask = uni.uploadFile({
							url: that.$API.upload(),
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'token': that.token
							},
							success: function(uploadFileRes) {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);
								var data = JSON.parse(uploadFileRes.data);
								uni.showToast({
									title: data.msg,
									icon: 'none'
								})
								if (data.code == 1) {
									that.imgurl = data.data.url;
								}
							},
							fail: function() {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);
							}
						});
						uploadTask.onProgressUpdate(function(res) {

						});
					}
				})
			},
			setSubtypeShow() {
				var that = this;
				if (that.sortText != '') {
					that.subtypeShow = true;
				} else {
					uni.showToast({
						title: that.$t('edit.addshop.plsbigcategory'),
						icon: 'none',
					});
				}
			},
			previewImage(imageList, image) {
				//预览图片
				uni.previewImage({
					urls: imageList,
					current: image
				});
			},
			getShopTypelist() {
				var that = this;
				var data = {
					"limit": 100,
					"token": that.token,
				};
				that.$Net.request({
					url: that.$API.shopTypeList(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.shopTypelist = res.data.data;
							var list = res.data.data;
							var sortList = [];
							for (var i in list) {
								if (list[i].parent == 0) {
									sortList.push(list[i]);
								}
							}
							that.sortList = sortList;

							that.sortSelect = sortList.map(item => {
								return {
									value: item.id,
									label: item.name
								};
							});
							if (that.sort > 0) {
								for (var s in sortList) {
									if (sortList[s].id == that.sort) {
										that.setSort(sortList[s], true);
									}
								}
							}
							that.isLoading = true;
							that.setloading();
						}
					},
					fail: function(res) {
						
					}
				});
			},
			setSort(data, noSub) {
				var that = this;
				that.sortShow = false;
				that.sort = data.id;
				that.sortText = data.name;
				if (that.sort != 0) {
					var list = that.shopTypelist;
					var subtypeList = [];
					for (var i in list) {
						if (list[i].parent == that.sort) {
							subtypeList.push(list[i]);
						}
					}
					that.subtypeList = subtypeList;

					that.subtypeSelect = subtypeList.map(item => {
						return {
							value: item.id,
							label: item.name
						};
					});
					if (!noSub) {
						if (subtypeList.length > 0) {
							that.subtype = subtypeList[0].id;
							that.subtypeText = subtypeList[0].name;
						} else {
							that.subtype = 0;
						}
					} else {
						if (subtypeList.length > 0) {
							for (var s in subtypeList) {
								if (subtypeList[s].id == that.subtype) {
									that.subtypeText = subtypeList[s].name;
								}
							}
						} else {
							that.subtype = 0;
						}
					}
				}
			},
			setloading() {
				var that = this;
				if (!that.isLoading) {
					uni.showLoading({
						title: that.$t('global.obtaindata'),
					});
				} else {
					uni.hideLoading();
				}
			},
			editPaidContent() {
				uni.navigateTo({
					url: '/pages/edit/payText?havePay=' + this.havePay + '&sid=' + this.id
				});
			},
			getInfo(id) {
				var that = this;
				var token = "";
				var data = {
					"key": id,
					"token": that.token,
				}
				that.$Net.request({
					url: that.$API.shopInfo(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.id) {
							that.title = res.data.title;
							that.category = res.data.type;
							that.imgurl = res.data.imgurl;
							that.num = res.data.num;
							that.sort = res.data.sort;
							that.subtype = res.data.subtype;
							that.text = res.data.text;
							that.havePay = true;
							var a = res.data.value;
							var b = res.data.price;
							var c = res.data.vipDiscount;
							var payData = {
								text: a,
								shopPice: b,
								shopDiscount: c
							};
							localStorage.setItem("payId" + res.data.id, JSON.stringify(payData));
							that.isLoading = true;
							that.setloading();
							if (that.sort > 0) {
								for (var s in that.sortList) {
									that.setSort(that.sortList[s], true);
									if (that.subtype) {
										let subtype = that.shopTypelist.find(item => item.id == that.subtype);
										if (subtype) {
											that.subtypeText = subtype.name;
										}
									}
								}
							}
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						});
					}
				});
			},

			back() {
				localStorage.removeItem('isSaveSp')
				uni.navigateBack({
					delta: 1
				});
			},
			toDraft() {
				uni.navigateTo({
					url: '/pages/forum/draftList'
				});
			},
			okBtn() {
				const nowDate = +new Date();
				uni.setStorageSync('modelView', nowDate);
				this.cancleBtn();
			},
			handleEditorFocus() {
				this.showContent = false;
				this.NavBar = this.StatusBar;
			},
			handleEditorBlur() {
				this.showContent = true;
				this.NavBar = that.CustomBar;
			},
			cancleBtn() {
				this.modelVisible = false;
			},
			toSpace(e) {
				this.isSpace = e.detail.value
			},
			submit() {
				var that = this;
				var type = that.type;
				if (type == "edit") {
					that.$refs.editor.save();
					setTimeout(function() {
						that.updateShop();
					}, 200)
				} else {
					that.$refs.editor.save()
					setTimeout(function() {
						that.addShop();
					}, 200)
				}
				// if(that.shopID!=-1){
				// 	that.mountShop();
				// }
			},
			onSave(e) {
				var that = this
				that.content = e.html;
			},
			addShop() {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: that.$t('edit.addshop.plsproducttitle'),
						icon: 'none'
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: that.$t('global.contextnoempty'),
						icon: 'none'
					});
					return false
				}
				if (that.sort == 0 && that.subtype == 0) {
					uni.showToast({
						title: that.$t('global.plsselclassify'),
						icon: 'none'
					});
					return false
				}
				var text = that.content;
				var isSpace = 0;
				var params = {
					'title': that.title,
					'type': 1,
					'imgurl': that.imgurl,
					'num': that.num,
					'integral': "0",
					'sort': that.sort,
					'subtype': that.subtype,
				}
				if (that.havePay && that.id != '0') {
					var payData = JSON.parse(localStorage.getItem("payId" + that.id));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				} else {
					var payData = JSON.parse(localStorage.getItem("payIdmy"));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				}
				var data = {
					"params": JSON.stringify(that.removeObjectEmptyKey(params)),
					"token": that.token,
					'text': text,
					"isSpace": isSpace,
					"isMd": 0
				}
				that.$Net.request({

					url: that.$API.addShop(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						if (res.data.code == 1) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
							localStorage.removeItem('payIdmy');
							setTimeout(function() {
								that.back();
							}, 1000)
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					},
				})
			},
			removeObjectEmptyKey(json) {
				var value;
				for (var key in json) {
					if (json.hasOwnProperty(key)) {
						value = json[key];
						if (value === undefined || value === '' || value === null) {
							delete json[key]
						}
					}
				}
				return json;
			},
			updateShop() {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: that.$t('edit.addshop.plsproducttitle'),
						icon: 'none'
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: that.$t('global.contextnoempty'),
						icon: 'none'
					});
					return false
				}
				if (that.sort == 0) {
					uni.showToast({
						title: that.$t('edit.addshop.plsbigcategory'),
						icon: 'none'
					});
					return false
				}
				var text = that.content;
				var isSpace = 0;
				var params = {
					'id': that.id,
					'title': that.title,
					'type': 1,
					'imgurl': that.imgurl,
					'num': that.num,
					'integral': "0",
					'sort': that.sort,
					'subtype': that.subtype,
				}
				if (that.havePay && that.id != '0') {
					var payData = JSON.parse(localStorage.getItem("payId" + that.id));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				} else {
					var payData = JSON.parse(localStorage.getItem("payIdmy"));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				}
				var data = {
					"params": JSON.stringify(that.removeObjectEmptyKey(params)),
					"token": that.token,
					'text': text,
					"isMd": 0
				}
				that.$Net.request({
					url: that.$API.editShop(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						if (res.data.code == 1) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
							localStorage.setItem('isShopEdit', 'true');
							setTimeout(function() {
								that.back();
							}, 1000)
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					},
				})
			},
			isback() {
				var that = this;
				var isSave = localStorage.getItem('isSaveSp');
				if (isSave == 'true') {
					that.back()
				} else {
					uni.showModal({
						title: that.$t('global.prompt'),
						content: that.$t('global.editnosave'),
						cancelText: that.$t('global.exit'),
						confirmText: that.$t('global.leave'),
						success: function(res) {
							if (res.confirm) {

							} else if (res.cancel) {
								that.back()
							}
						}
					});
				}
			}
		}
	}
</script>

<style>
	.post {
		display: flex;
		flex: 1;
		flex-direction: column;
		justify-content: space-between;
	}
</style>